#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
#include <fstream>
#include <cassert>
#include "../comm/commfun.hpp"

using namespace std;
using namespace ns_commfunc;

namespace ns_model
{

    struct Question
    {
        string id;
        string titlename;
        string level;
        int cpu_limit;
        int mem_limit;

        string desc;
        string header;
        string tail;
    };

    const string queslist_path = "./questions/questionslist.txt";
    const string ques_path = "./questions/";

    class model
    {
    private:
        //将题目信息加载进内存
        unordered_map<string, Question> questions;
    public:
        model()
        {
            assert(LoadQuestions(queslist_path));
        }

        ~model(){}

        //获取整个题库
        bool GetQuestions(vector<Question>& ques)
        {
            if(questions.size() == 0) return false;

            for(auto& q : questions)
            {
                //获取
                ques.push_back(q.second);
            }

            return true;
        }

        bool GetOneQuestion(string& number, Question& ques)
        {
            auto it = questions.find(number);
            if(it == questions.end()) return false;

            ques = it->second;
            return true;
        }

        bool LoadQuestions(const string& filepath)
        {
            ifstream in(filepath);
            if(!in.is_open())
            {
                return false;
            }

            string line;
            while(getline(in, line))
            {
                vector<string> vs;
                StringUtil::SplitStr(line, vs, " ");

                Question temp;
                temp.id = vs[0];
                temp.titlename = vs[1];
                temp.level = vs[2];
                temp.cpu_limit = stoi(vs[3]);
                temp.mem_limit = stoi(vs[4]);

                string path = ques_path + temp.id;
                FileUtil::Readfile(path + "/desc.txt", temp.desc, true);
                FileUtil::Readfile(path + "/header.cpp", temp.header, true);
                FileUtil::Readfile(path + "/tail.cpp", temp.tail, true);

                questions.insert({temp.id, temp});
            }

            in.close();
            return true;
        }

    };
}
